//---------------------------------------------------------------------------

#include "vcl_stl.h"
#pragma hdrstop

#include "h_lic.h"
#include "h_tea.h"
//---------------------------------------------------------------------------

static const char *GlobalKey = "SIM-BAT 2.9.0   ";

void __fastcall MakeLic(unsigned char Buf[LIC_BUF_LEN], const UTF8String &LicUser,
   int ExpireDate, int LicQty, const UTF8String &LicProject)
{
   char TmpBuf[200 + 1];
   snprintf(TmpBuf, 200, "%-32.32s%08d%04d1234%-32.32s", LicUser.c_str(),
      ExpireDate, LicQty, LicProject.c_str());
   memcpy(Buf + 0x350, TmpBuf, 32 + 8 + 8 + 32);
   EncryptLic(Buf);
}

void __fastcall EncryptLic(unsigned char Buf[LIC_BUF_LEN])
{
   unsigned char Key[16];

   memcpy(Key, GlobalKey, 16);

   for ( int i = 0; i < 16; i++ )
   {
      Key[i] ^= 0xa3;
   }

   BkTeaEncrypt(Buf, Key, LIC_BUF_LEN);
}

void __fastcall DecryptLic(unsigned char Buf[LIC_BUF_LEN])
{
   unsigned char Key[16];

   memcpy(Key, GlobalKey, 16);

   for ( int i = 0; i < 16; i++ )
   {
      Key[i] ^= 0xa3;
   }

   BkTeaDecrypt(Buf, Key, LIC_BUF_LEN);
}

bool __fastcall GetLic(const unsigned char ABuf[LIC_BUF_LEN], UTF8String &LicUser,
   int &ExpireDate, int &LicQty, UTF8String &LicProject)
{
   unsigned char Key[16];

   memcpy(Key, GlobalKey, 16);

   for ( int i = 0; i < 16; i++ )
   {
      Key[i] ^= 0xa3;
   }

   char Buf[LIC_BUF_LEN];
   memcpy(Buf, ABuf, LIC_BUF_LEN);
   BkTeaDecrypt(Buf, Key, LIC_BUF_LEN);

   if ( memcmp(Buf + 0x350 + 32 + 8 + 4, "1234", 4) != 0 )
   {
      return false;
   }

   LicUser = UTF8String(Buf + 0x350, 32).TrimRight();
   ExpireDate = UTF8String(Buf + 0x350 + 32, 8).ToIntDef(0);
   LicQty = UTF8String(Buf + 0x350 + 32 + 8, 4).ToIntDef(2);
   LicProject = UTF8String(Buf + 0x350 + 32 + 8 + 8, 32).TrimRight();
   return true;
}

#pragma package(smart_init)
